package core.dao.impl;

import javax.persistence.NoResultException;
import javax.persistence.Query;

import org.springframework.util.Assert;

import commons.dao.impl.GenericDaoImpl;
import core.dao.UserDao;
import core.model.UserEntity;


public class UserDaoImpl extends GenericDaoImpl<UserEntity, Long> implements UserDao {

    public UserDaoImpl() {
            super(UserEntity.class);
    }

    /**
     * Queries database for user name availability
     *
     * @param userName
     * @return true if available
     */
    public boolean checkAvailable(String userName) {
            Assert.notNull(userName);
           
            Query query = getEntityManager()
                    .createQuery("select count(*) from " + getPersistentClass().getSimpleName()
                                    + " u where u.userName = :userName").setParameter("userName", userName);
           
            Long count = (Long) query.getSingleResult();
           
            return count < 1;
    }

    /**
     * Queries user by username
     *
     * @param userName
     * @return User entity
     */
    public UserEntity loadUserByUserName(String userName) {
            Assert.notNull(userName);
           
            UserEntity user = null;
           
            Query query = getEntityManager().createQuery("select u from " + getPersistentClass().getSimpleName()
                            + " u where u.userName = :userName").setParameter("userName", userName);
           
            try {
                    user = (UserEntity) query.getSingleResult();
            } catch(NoResultException e) {
                    //do nothing
            }
           
            return user;
    }

}

